﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Furion;
using System.IdentityModel.Tokens.Jwt;
using Furion.DataEncryption;

namespace furion.blog.Utils
{
    public class JwtUtil
    {
        /// <summary>
        /// 调用Furion框架生成token
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string CreateToken(Dictionary<string,object> dic) {
           return JWTEncryption.Encrypt(dic);
        }


        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="claims"></param>
        /// <returns>token(token),long(有效期至)</returns>
        public static (string,long) CreateToken(Claim[] claims)
        {
            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(App.Configuration["JWT:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 从 appsettings.json 中读取Expires
            var expires = Convert.ToDouble(App.Configuration["JWT:Expires"]);

            // 6. 根据以上，生成token
            var token = new JwtSecurityToken(
                App.Configuration["JWT:Issuer"],     //Issuer
                App.Configuration["JWT:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(expires),   //expires
                signingCredentials               //Credentials
            );

            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            long exp = DateTimeOffset.UtcNow.AddHours(expires * 24).ToUnixTimeSeconds();
            return (jwtToken , exp);
        }
    }
}
